package com.jpa.demo.repository.support;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 模拟EntityManager对数据库的操作，采用内存存储
 */
public class MyEntityManager {

    private final Map<Class<?>, Map<Object, Object>> database = new HashMap<>();

    public <T> T persist(T entity) {
        database.computeIfAbsent(entity.getClass(), k -> new HashMap<>())
                .put(getId(entity), entity);
        return entity;
    }

    public <T, ID> T find(Class<T> entityClass, ID id) {
        return entityClass.cast(database.getOrDefault(entityClass, Collections.emptyMap()).get(id));
    }

    public <T> List<T> findAll(Class<T> entityClass) {
        Map<?, ?> entityMap = database.getOrDefault(entityClass, Collections.emptyMap());

        return entityMap.values().stream()
                .map(entityClass::cast)
                .collect(Collectors.toList());
    }

    public <T, ID> void delete(Class<T> entityClass, ID id) {
        database.getOrDefault(entityClass, Collections.emptyMap()).remove(id);
    }

    private Object getId(Object entity) {
        try {
            return entity.getClass().getMethod("getId").invoke(entity);
        } catch (Exception e) {
            throw new RuntimeException("Entity must have getId() method");
        }
    }
}

